<template>
	<div>
		<el-button icon="el-icon-d-arrow-left" type="info" plain @click="$router.go(-1)" size="small">返回
		</el-button>
		<h2>接口请求测试</h2>
		<el-tabs tab-position="top" type="border-card" @tab-click="handleTabClick">
			<el-tab-pane :label="'接口请求测试'">
				<div class="mycontent">

					<h2>访问接口</h2>

					<h4>URL：</h4>
					<el-input v-model="url"></el-input>


					<h4>Header：</h4>

					<el-form label-width="150px" style="width: 600px" size="medium">
            <el-form-item label="Token 名字">
              <el-input v-model="tokenName" ></el-input>
            </el-form-item>
            <el-form-item label="Token 值">
              <el-input v-model="tokenValue" ></el-input>
            </el-form-item>
						<el-form-item label="Content-Type">
							<el-input v-model="contentType" disabled></el-input>
						</el-form-item>

					</el-form>

					<h4>参数：</h4>
					<div class="textarea">
						<el-input v-model="jsonParam" :placeholder="'输入json参数'" type="textarea" rows="10"
							v-show="contentType === CONTENT_TYPE.JSON"></el-input>
					</div>
					<el-form label-width="200px" style="width: 650px" size="medium"
						v-show="contentType === CONTENT_TYPE.FORM_URLENCODED">
						<el-form-item v-for="(item,index) in inParams" :key="item.id" style="margin-bottom: 5px">
							<template slot="label">
								<data-tag :name="item.name" :type="item.type"></data-tag>
							</template>
							<el-input v-model="item.value" v-if="!item.type.startsWith('Array')" :placeholder="item.note">
								<!--          <template slot="append">{{ item.type }}</template>-->
							</el-input>
							<div v-show="item.type.startsWith('Array')">
								<div v-for="(childItem,childIndex) in item.values" :key="childIndex">
									<el-input v-model="childItem.va" :placeholder="item.note" style="width: 400px">
									</el-input>
									<el-button slot="append" icon="el-icon-delete" type="danger" circle size="mini"
										@click="deleteRow(index,childIndex)" style="margin-left: 4px;"></el-button>
								</div>

								<el-button icon="el-icon-plus" type="primary" circle size="mini" @click="addRow(index)"></el-button>
							</div>
						</el-form-item>

					</el-form>
					<el-button @click="request">发送请求</el-button>

					<h4>返回结果：</h4>

					<el-table :data="tableData" v-show="showTable" size="mini" border stripe max-height="700">
						<el-table-column :prop="item" :label="item" v-for="item in keys" :key="item"></el-table-column>
					</el-table>
					<el-input type="textarea" v-model="response" :autosize="{ minRows: 5, maxRows: 20 }" class="my"
						v-show="!showTable"></el-input>

					<el-button size="small" @click="format" class="button">JSON格式化
					</el-button>

				</div>
			</el-tab-pane>

		</el-tabs>

	</div>

</template>

<script>

const CONTENT_TYPE = {
  FORM_URLENCODED: "application/x-www-form-urlencoded",
  JSON: "application/json"
}

const PREVILEGE = {
  PRIVATE: 0,
  PUBLIC: 1
}

	import axios from 'axios';


	import dataTag from './components/dataTag.vue';
  import {getCore} from "@framework-core/api/core/api";
  import website  from '@framework-core/config/website';

	export default {
		name: "onlineTest",
		components: {
			dataTag },
		data () {
			return {
				CONTENT_TYPE: Object.freeze(CONTENT_TYPE),
				PREVILEGE: Object.freeze(PREVILEGE),
				api: {},
        inParams: [],
				path: null,
        authority: 1,
				address: website.baseUrl,
				response: null,
				keys: [],
				tableData: [],
				showTable: false,
        tokenName:null,
        tokenValue:null,
				url: "",
				contentType: null,
				jsonParam: null
			};
		},
		methods: {

			 getDetail (id) {
         getCore("/apis/apisConfig",id).then((response) => {
          let configData =  response.data.data.data
           debugger
					this.path=configData.path;
					this.authority=configData.authority;

          if(configData.inParams!=''&&configData.inParams!=null){
          	let inParams=JSON.parse(configData.inParams);
            inParams.forEach((t) => {
          						if (t.type.startsWith("Array")) {
          							t.values=[{ va: "" }];
          						}
          					});

          	this.inParams=inParams;
          }


          this.url=`${this.address}/api/apis/call/${this.path}`;
					this.contentType=configData.contentType;
					//this.jsonParam=configData.jsonParam;
				}).catch((error) => {
					this.$message.error(error);
				});
			},
			async getAddress () {
        this.url=`${this.address}/${this.path}`;
			},
			request () {

				this.response=null;
				let p={};
        let partam = {};
				if (this.contentType===CONTENT_TYPE.FORM_URLENCODED) {
					this.inParams.forEach((t) => {
						//构造数组类型的请求参数
						if (t.type.startsWith("Array")) {
							const values=t.values.map((item) => item.va);
							p[t.name]=values;
						} else {
							p[t.name]=t.value;
						}
					});

          //partam = qs.stringify(p, { indices: false });
				} else if (this.contentType===CONTENT_TYPE.JSON) {

					p=this.jsonParam;
          alert(p)
          if(p){
            partam = eval('('+p+')');
          }
				}

				console.info(partam)
				// let url = `http://${this.address}/api/${this.path}`
        let headersConfig = {};
        headersConfig["Content-Type"] =  this.contentType;
        if(this.tokenName){
          headersConfig[this.tokenName] =  this.tokenValue;
        }
				axios.post(this.url, partam, {
						headers: headersConfig,
					})
					.then((response) => {
						if (response.data.data.data) {
							this.showTable=false;
							this.response=JSON.stringify(response.data.data.data);
						}
					})
					.catch((error) => {
						// 只要状态码不是200都会进入catch逻辑
						this.$message.error(error);
					});
			},
			format () {
				const o=JSON.parse(this.response);
				this.response=JSON.stringify(o, null, 4);
			},
			tableShow () {
				if (this.response==null) return;
				let obj=JSON.parse(this.response);
				if (obj.success) {
					this.tableData=obj.data;
					if (obj.data.length>0) {
						this.keys=Object.keys(obj.data[0]);
					} else {
						return;
					}
				} else {
					return;
				}
				this.showTable=true;
			},
			tableHide () {
				this.showTable=false;
			},
			addRow (index) {
				this.inParams[index].values.push({ va: null });
			},
			deleteRow (index, childIndex) {
				this.inParams[index].values.splice(childIndex, 1);
			},
			handleTabClick (tab) {
				const label=tab.label;
				if (label===this.$t('m.request_demo')) {
					this.$nextTick(() => {
						this.$refs.callExample.refresh();
					});
				}
			},
		},
		created () {
			this.getDetail(this.$route.query.id);
			this.getAddress();

		},
		computed: {
			// url(){
			//   return `http://${ this.address }/api/${ this.path }`
			// }
		},
	};
</script>

<style scoped lang="scss">
	.my>.el-textarea__inner {
		font-family: "Consolas", Helvetica, Arial, sans-serif;
		/*font-size: 18px;*/
	}

	h2 {
		margin-bottom: 25px;
		text-align: center;
	}

	h4 {
		margin: 10px 0;
	}

	.path {
		font-size: 16px;
		border: 1px #ccc solid;
		padding: 10px 10px;
	}

	.url {
		padding: 5px;
		border: 1px solid #ccc;

		.input {
			background-color: rgba(1, 87, 36, 0.06);
			font-size: 16px;
			padding: 5px;
			border-width: 0px;
			outline: none;
		}
	}

	.button {
		margin: 10px 10px 10px 0;
	}

	.textarea {
		::v-deep .el-textarea__inner {
			font-family: "Consolas", Helvetica, Arial, sans-serif !important;
			font-size: 16px !important;
			line-height: 20px;
		}
	}
</style>
